class ProgrammingTrainingPartner(AITrainingPartner):
    """编程练习AI陪练"""

    def __init__(self, name, programming_language="python"):
        super().__init__(name)
        self.language = programming_language
        self.exercises = self._load_exercises()

    def _load_exercises(self):
        return {
            "easy": [
                {
                    "title": "两数之和",
                    "description": "编写一个函数，接受两个数字参数并返回它们的和",
                    "function_name": "add_numbers",
                    "test_cases": [
                        {"input": (2, 3), "output": 5},
                        {"input": (-1, 1), "output": 0},
                        {"input": (0, 0), "output": 0}
                    ]
                }
            ],
            "medium": [
                {
                    "title": "斐波那契数列",
                    "description": "编写一个函数，返回第n个斐波那契数",
                    "function_name": "fibonacci",
                    "test_cases": [
                        {"input": (1,), "output": 1},
                        {"input": (5,), "output": 5},
                        {"input": (10,), "output": 55}
                    ]
                }
            ],
            "hard": [
                {
                    "title": "快速排序",
                    "description": "实现快速排序算法",
                    "function_name": "quicksort",
                    "test_cases": [
                        {"input": ([3, 1, 2],), "output": [1, 2, 3]},
                        {"input": ([5, 2, 8, 1, 9],), "output": [1, 2, 5, 8, 9]}
                    ]
                }
            ]
        }

    def generate_exercise(self, topic="algorithm"):
        """生成编程练习"""
        level_exercises = self.exercises[self.difficulty]
        exercise = random.choice(level_exercises)

        return {
            "type": "programming",
            "title": exercise["title"],
            "description": exercise["description"],
            "function_name": exercise["function_name"],
            "test_cases": exercise["test_cases"],
            "difficulty": self.difficulty
        }

    def evaluate_response(self, user_code, exercise):
        """评估编程代码"""
        try:
            # 在实际应用中，这里会在安全环境中执行代码
            # 这里简化为模式匹配
            test_cases = exercise["test_cases"]
            passed = 0

            # 简单的代码质量检查
            code_quality = self._check_code_quality(user_code)

            # 模拟测试用例通过情况
            for test_case in test_cases:
                # 实际中会执行代码并比较结果
                if random.random() > 0.3:  # 模拟70%通过率
                    passed += 1

            score = passed / len(test_cases)

            return {
                "score": score,
                "passed_tests": passed,
                "total_tests": len(test_cases),
                "code_quality": code_quality,
                "feedback": self._generate_code_feedback(score, code_quality)
            }

        except Exception as e:
            return {
                "score": 0,
                "error": str(e),
                "feedback": f"代码执行出错: {str(e)}"
            }

    def _check_code_quality(self, code):
        """检查代码质量"""
        quality_score = 0.5  # 基础分

        # 简单的启发式检查
        if "//" not in code and "#" not in code:
            quality_score -= 0.1  # 缺少注释

        if len(code.split('\n')) > 20:
            quality_score -= 0.1  # 代码太长

        if "for" in code or "while" in code:
            quality_score += 0.1  # 使用了循环

        return max(0.1, min(1.0, quality_score))

    def _generate_code_feedback(self, test_score, quality_score):
        """生成代码反馈"""
        if test_score == 1.0:
            if quality_score > 0.8:
                return "优秀！所有测试通过且代码质量很高。"
            else:
                return "所有测试通过，但可以改进代码质量。"
        elif test_score > 0.7:
            return "大部分测试通过，继续努力！"
        else:
            return "需要更多练习，建议查看相关算法知识。"

    def provide_feedback(self, user_response, evaluation):
        """提供编程反馈"""
        base_feedback = evaluation["feedback"]

        if "error" in evaluation:
            return f"错误: {evaluation['error']}\n{base_feedback}"

        additional_tips = []

        if evaluation["score"] < 0.5:
            additional_tips.append("建议先理解问题需求，再开始编码。")
        if evaluation["code_quality"] < 0.6:
            additional_tips.append("注意代码可读性，添加适当的注释。")

        tips = " ".join(additional_tips)
        return f"{base_feedback} {tips}"